package com.lt.common.helper;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtHelper {

    //token的过期时间
    private static long tokenExpiration = 24*60*60*1000;
    //签名的密钥 根据所给的字符串通过算法获得加密
    private static String tokenSignKey = "123456";

    /**
     * 根据所给的参数获取token
     * @param userId
     * @param userName
     * @return
     */
    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                //头部信息
                .setHeaderParam("typ","JWT")//令牌类型
                .setHeaderParam("alg","HS256")//签名算法

                //载荷:自定义信息，需要加密参数
                .claim("userId", userId)
                .claim("userName", userName)

                .setSubject("YYGH-USER")//分类
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))//过期时间

                //签名哈希算法
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    /**
     * 根据token得到了用户id
     * @param token
     * @return
     */
    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
    }

    /**
     * 根据了token得到了用户名
     * @param token
     * @return
     */
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)) return "";
        Jws<Claims> claimsJws
                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("userName");
    }

    /**
     * 测试类
     * @param args
     */
    public static void main(String[] args) {
        String token = JwtHelper.createToken(1L, "jack");
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getUserName(token));
    }
}
